package com.och.mrcp.core.audio;

import lombok.extern.slf4j.Slf4j;

/**
 * 音频编解码器
 * 支持各种RTP负载类型转换为PCM格式
 * RFC 3551 - RTP Profile for Audio and Video Conferences
 */
@Slf4j
public class AudioCodec {
    
    /**
     * RTP负载类型枚举
     */
    public enum PayloadType {
        PCMU(0, "G.711 μ-law", 8000, 1),
        RESERVED_1(1, "Reserved", 0, 0),
        RESERVED_2(2, "Reserved", 0, 0),
        GSM(3, "GSM", 8000, 1),
        G723(4, "G.723", 8000, 1),
        DVI4_8K(5, "DVI4", 8000, 1),
        DVI4_16K(6, "DVI4", 16000, 1),
        LPC(7, "LPC", 8000, 1),
        PCMA(8, "G.711 A-law", 8000, 1),
        G722(9, "G.722", 8000, 1),
        L16_2CH(10, "L16", 44100, 2),
        L16_1CH(11, "L16", 44100, 1),
        QCELP(12, "QCELP", 8000, 1),
        CN(13, "Comfort Noise", 8000, 1),
        MPA(14, "MPEG Audio", 90000, 1),
        G728(15, "G.728", 8000, 1),
        DVI4_11K(16, "DVI4", 11025, 1),
        DVI4_22K(17, "DVI4", 22050, 1),
        G729(18, "G.729", 8000, 1);
        
        private final int value;
        private final String name;
        private final int sampleRate;
        private final int channels;
        
        PayloadType(int value, String name, int sampleRate, int channels) {
            this.value = value;
            this.name = name;
            this.sampleRate = sampleRate;
            this.channels = channels;
        }
        
        public int getValue() { return value; }
        public String getName() { return name; }
        public int getSampleRate() { return sampleRate; }
        public int getChannels() { return channels; }
        
        public static PayloadType fromValue(int value) {
            for (PayloadType type : values()) {
                if (type.value == value) {
                    return type;
                }
            }
            return null;
        }
    }
    
    /**
     * 将RTP负载数据转换为PCM格式
     * 
     * @param payloadType RTP负载类型
     * @param audioData   原始音频数据
     * @return PCM格式的音频数据
     */
    public static byte[] convertToPcm(int payloadType, byte[] audioData) {
        if (audioData == null || audioData.length == 0) {
            log.warn("Empty audio data for payload type: {}", payloadType);
            return audioData;
        }
        
        PayloadType type = PayloadType.fromValue(payloadType);
        if (type == null) {
            log.warn("Unsupported payload type: {}, returning original data", payloadType);
            return audioData;
        }
        
        try {
            switch (type) {
                case PCMU:
                    return convertPcmuToPcm(audioData);
                case PCMA:
                    return convertPcmaToPcm(audioData);
                case L16_1CH:
                case L16_2CH:
                    return convertL16ToPcm(audioData);
                case G722:
                    return convertG722ToPcm(audioData);
                case G729:
                    return convertG729ToPcm(audioData);
                default:
                    log.debug("Payload type {} ({}) not specifically handled, assuming PCM", 
                            payloadType, type.getName());
                    return audioData; // 假设已经是PCM或兼容格式
            }
        } catch (Exception e) {
            log.error("Error converting payload type {} to PCM: {}", payloadType, e.getMessage(), e);
            return audioData; // 返回原始数据作为fallback
        }
    }
    
    /**
     * 转换 G.711 μ-law 到 16位PCM
     * RFC 3551 Section 4.5.14
     */
    private static byte[] convertPcmuToPcm(byte[] pcmuData) {
        byte[] pcmData = new byte[pcmuData.length * 2]; // 16位PCM需要2倍空间
        
        for (int i = 0; i < pcmuData.length; i++) {
            short pcmSample = muLawToPcm(pcmuData[i] & 0xFF);
            // 小端序存储16位PCM
            pcmData[i * 2] = (byte) (pcmSample & 0xFF);
            pcmData[i * 2 + 1] = (byte) ((pcmSample >> 8) & 0xFF);
        }
        
        log.debug("Converted PCMU to PCM: {} bytes -> {} bytes", pcmuData.length, pcmData.length);
        return pcmData;
    }
    
    /**
     * 转换 G.711 A-law 到 16位PCM
     * RFC 3551 Section 4.5.14
     */
    private static byte[] convertPcmaToPcm(byte[] pcmaData) {
        byte[] pcmData = new byte[pcmaData.length * 2]; // 16位PCM需要2倍空间
        
        for (int i = 0; i < pcmaData.length; i++) {
            short pcmSample = aLawToPcm(pcmaData[i] & 0xFF);
            // 小端序存储16位PCM
            pcmData[i * 2] = (byte) (pcmSample & 0xFF);
            pcmData[i * 2 + 1] = (byte) ((pcmSample >> 8) & 0xFF);
        }
        
        log.debug("Converted PCMA to PCM: {} bytes -> {} bytes", pcmaData.length, pcmData.length);
        return pcmData;
    }
    
    /**
     * 转换 L16 (线性16位) 到 PCM
     * L16本身就是PCM格式，只需要处理字节序
     */
    private static byte[] convertL16ToPcm(byte[] l16Data) {
        // L16已经是16位线性PCM，可能需要字节序转换
        // 通常网络字节序是大端序，需要转换为小端序
        byte[] pcmData = new byte[l16Data.length];
        
        for (int i = 0; i < l16Data.length; i += 2) {
            if (i + 1 < l16Data.length) {
                // 大端序转小端序
                pcmData[i] = l16Data[i + 1];
                pcmData[i + 1] = l16Data[i];
            }
        }
        
        log.debug("Converted L16 to PCM: {} bytes (byte order conversion)", l16Data.length);
        return pcmData;
    }
    
    /**
     * 转换 G.722 到 PCM
     * 注意：这是一个简化实现，真实的G.722需要复杂的解码算法
     */
    private static byte[] convertG722ToPcm(byte[] g722Data) {
        log.warn("G.722 to PCM conversion not fully implemented, returning original data");
        // TODO: 实现完整的G.722解码
        return g722Data;
    }
    
    /**
     * 转换 G.729 到 PCM
     * 注意：这是一个简化实现，真实的G.729需要复杂的解码算法
     */
    private static byte[] convertG729ToPcm(byte[] g729Data) {
        log.warn("G.729 to PCM conversion not fully implemented, returning original data");
        // TODO: 实现完整的G.729解码
        return g729Data;
    }
    
    /**
     * μ-law解码表 (ITU-T G.711)
     */
    private static final short[] MU_LAW_DECODE_TABLE = {
        -32124, -31100, -30076, -29052, -28028, -27004, -25980, -24956,
        -23932, -22908, -21884, -20860, -19836, -18812, -17788, -16764,
        -15996, -15484, -14972, -14460, -13948, -13436, -12924, -12412,
        -11900, -11388, -10876, -10364, -9852, -9340, -8828, -8316,
        -7932, -7676, -7420, -7164, -6908, -6652, -6396, -6140,
        -5884, -5628, -5372, -5116, -4860, -4604, -4348, -4092,
        -3900, -3772, -3644, -3516, -3388, -3260, -3132, -3004,
        -2876, -2748, -2620, -2492, -2364, -2236, -2108, -1980,
        -1884, -1820, -1756, -1692, -1628, -1564, -1500, -1436,
        -1372, -1308, -1244, -1180, -1116, -1052, -988, -924,
        -876, -844, -812, -780, -748, -716, -684, -652,
        -620, -588, -556, -524, -492, -460, -428, -396,
        -372, -356, -340, -324, -308, -292, -276, -260,
        -244, -228, -212, -196, -180, -164, -148, -132,
        -120, -112, -104, -96, -88, -80, -72, -64,
        -56, -48, -40, -32, -24, -16, -8, 0,
        32124, 31100, 30076, 29052, 28028, 27004, 25980, 24956,
        23932, 22908, 21884, 20860, 19836, 18812, 17788, 16764,
        15996, 15484, 14972, 14460, 13948, 13436, 12924, 12412,
        11900, 11388, 10876, 10364, 9852, 9340, 8828, 8316,
        7932, 7676, 7420, 7164, 6908, 6652, 6396, 6140,
        5884, 5628, 5372, 5116, 4860, 4604, 4348, 4092,
        3900, 3772, 3644, 3516, 3388, 3260, 3132, 3004,
        2876, 2748, 2620, 2492, 2364, 2236, 2108, 1980,
        1884, 1820, 1756, 1692, 1628, 1564, 1500, 1436,
        1372, 1308, 1244, 1180, 1116, 1052, 988, 924,
        876, 844, 812, 780, 748, 716, 684, 652,
        620, 588, 556, 524, 492, 460, 428, 396,
        372, 356, 340, 324, 308, 292, 276, 260,
        244, 228, 212, 196, 180, 164, 148, 132,
        120, 112, 104, 96, 88, 80, 72, 64,
        56, 48, 40, 32, 24, 16, 8, 0
    };
    
    /**
     * A-law解码表 (ITU-T G.711)
     */
    private static final short[] A_LAW_DECODE_TABLE = {
        -5504, -5248, -6016, -5760, -4480, -4224, -4992, -4736,
        -7552, -7296, -8064, -7808, -6528, -6272, -7040, -6784,
        -2752, -2624, -3008, -2880, -2240, -2112, -2496, -2368,
        -3776, -3648, -4032, -3904, -3264, -3136, -3520, -3392,
        -22016, -20992, -24064, -23040, -17920, -16896, -19968, -18944,
        -30208, -29184, -32256, -31232, -26112, -25088, -28160, -27136,
        -11008, -10496, -12032, -11520, -8960, -8448, -9984, -9472,
        -15104, -14592, -16128, -15616, -13056, -12544, -14080, -13568,
        -344, -328, -376, -360, -280, -264, -312, -296,
        -472, -456, -504, -488, -408, -392, -440, -424,
        -88, -72, -120, -104, -24, -8, -56, -40,
        -216, -200, -248, -232, -152, -136, -184, -168,
        -1376, -1312, -1504, -1440, -1120, -1056, -1248, -1184,
        -1888, -1824, -2016, -1952, -1632, -1568, -1760, -1696,
        -688, -656, -752, -720, -560, -528, -624, -592,
        -944, -912, -1008, -976, -816, -784, -880, -848,
        5504, 5248, 6016, 5760, 4480, 4224, 4992, 4736,
        7552, 7296, 8064, 7808, 6528, 6272, 7040, 6784,
        2752, 2624, 3008, 2880, 2240, 2112, 2496, 2368,
        3776, 3648, 4032, 3904, 3264, 3136, 3520, 3392,
        22016, 20992, 24064, 23040, 17920, 16896, 19968, 18944,
        30208, 29184, 32256, 31232, 26112, 25088, 28160, 27136,
        11008, 10496, 12032, 11520, 8960, 8448, 9984, 9472,
        15104, 14592, 16128, 15616, 13056, 12544, 14080, 13568,
        344, 328, 376, 360, 280, 264, 312, 296,
        472, 456, 504, 488, 408, 392, 440, 424,
        88, 72, 120, 104, 24, 8, 56, 40,
        216, 200, 248, 232, 152, 136, 184, 168,
        1376, 1312, 1504, 1440, 1120, 1056, 1248, 1184,
        1888, 1824, 2016, 1952, 1632, 1568, 1760, 1696,
        688, 656, 752, 720, 560, 528, 624, 592,
        944, 912, 1008, 976, 816, 784, 880, 848
    };
    
    /**
     * μ-law解码
     */
    private static short muLawToPcm(int muLawSample) {
        return MU_LAW_DECODE_TABLE[muLawSample];
    }
    
    /**
     * A-law解码
     */
    private static short aLawToPcm(int aLawSample) {
        return A_LAW_DECODE_TABLE[aLawSample];
    }
    
    /**
     * 检查负载类型是否受支持
     */
    public static boolean isSupported(int payloadType) {
        PayloadType type = PayloadType.fromValue(payloadType);
        if (type == null) {
            return false;
        }
        
        // 目前支持的类型
        switch (type) {
            case PCMU:
            case PCMA:
            case L16_1CH:
            case L16_2CH:
                return true;
            case G722:
            case G729:
                return false; // 暂时不支持，需要复杂的解码算法
            default:
                return false;
        }
    }
    
    /**
     * 获取负载类型信息
     */
    public static String getPayloadTypeInfo(int payloadType) {
        PayloadType type = PayloadType.fromValue(payloadType);
        if (type == null) {
            return "Unknown payload type: " + payloadType;
        }
        
        return String.format("%s (PT=%d, %dHz, %dch)", 
                type.getName(), type.getValue(), type.getSampleRate(), type.getChannels());
    }
}
